package com.apache.uct.service.impl;

import java.util.List;

import org.springframework.beans.BeanUtils;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.database.model.Page;
import com.apache.exception.BusinessException;
import com.apache.uct.common.entity.User;
import com.apache.uct.common.entity.UserBack;
import com.apache.uct.manager.UserManager;
import com.apache.uct.util.UctStringUtil;

public class UserManagerImpl implements UserManager {

	protected IDao userDao;
	protected final String entityName = "com.apache.uct.common.entity.User";
	private PluginConnector userListPlugin;

	public void setUserDao(IDao userDao) {
		this.userDao = userDao;
	}

	public void setUserListPlugin(PluginConnector userListPlugin) {
		this.userListPlugin = userListPlugin;
	}

	public String saveInfo(ParamsVo<User> vo) throws BusinessException {
		User user = vo.getObj();
		String infoId = String.valueOf(vo.getInfoId());
		//定义对象缓存KEY,如果不需要缓存对象请不要对变量赋值，如果要缓存对象建议使用infoId
		String cacheKey = "";
		//String cacheKey="user_"+infoId;

		if (Validator.isNotNull(infoId)) {
			user.setUserId(infoId);
		} else {
			infoId = Validator.generate();
			user.setUserId(infoId);
		}

		MethodParam param = new MethodParam("User", cacheKey, "", entityName);
		param.setVaule(user);
		if (userDao.insert(param)) {

			return infoId;
		}
		return "";
	}

	public boolean editInfo(ParamsVo<User> vo) throws BusinessException {
		User user = vo.getObj();
		if (Validator.isNotNull(user.getUserId())) {
			String cacheKey = "";
			//String cacheKey="user_"+user.getUserId();
			MethodParam param = new MethodParam("User", cacheKey, "", entityName);
			param.setVaule(user);
			return userDao.edit(param);
		}
		return false;
	}

	public boolean deleteInfo(ParamsVo<User> vo) throws BusinessException {
		String infoId = vo.getInfoId();
		if (Validator.isNull(infoId)) {
			return false;
		}
		String cacheKey = "";
		//String cacheKey="user_"+infoId;
		String mark = Validator.getDefaultStr(String.valueOf(vo.getParams("isDelete")), "true");
		MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
		param.setInfoId(infoId);
		User info = (User) userDao.selectById(param);
		if (Validator.isEmpty(info)) {
			return false;
		}
		info.setUserStatus(-1);
		param.setVaule(info);//此处需要先将状态值赋值为删除状态
		if ("false".equals(mark)) {//逻辑删除
			param.setKey("User");
			return userDao.edit(param);
		} else {
			param.setParams("userId", infoId);
			param.setDelete(true);
			boolean flag = userDao.delete(param);
			if (flag && "T".equals(vo.getParams("isBack"))) {//删除用户
				param = new MethodParam("UserBack", cacheKey, "", UserBack.class.getName());
				UserBack back = new UserBack();
				BeanUtils.copyProperties(info, back);
				param.setVaule(back);
				userDao.insert(param);
			}
			return flag;
		}
	}

	public Object getInfoById(ParamsVo<User> vo) {
		String infoId = vo.getInfoId();
		String cacheKey = "";
		//String cacheKey="user_"+infoId;
		if (Validator.isNull(infoId)) {
			return null;
		}
		MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
		param.setInfoId(infoId);
		return userDao.selectById(param);
	}

	public Object execute(ParamsVo<User> vo) {
		String key = vo.getKey();
		try {
			if ("byUserEname".equals(key)) {
				return getUserByUserEname(String.valueOf(vo.getParams("userEname")));
			} else if ("checkUserEname".equals(key)) {
				String msg = getUserByUserEname(vo.getObj().getUserEname(), vo.getObj().getEmail(), vo.getObj()
						.getMobile());
				return msg;
			} else if ("userList".equals(key)) {//获取用户列表
				ResultEntity entity = (ResultEntity) userListPlugin.execute(vo);
				return entity.getEntity();
			} else if ("userAttr".equals(key)) {
				User user = getUserByUserIdOrUserEname(vo.getObj());
				return user;
			}
		} catch (Exception e) {

		}
		return null;
	}

	//按用户名获取用户信息
	private User getUserByUserEname(String userEname) {
		if (Validator.isNull(userEname))
			return null;
		String sql = " and userEname=: userEname";
		boolean mark = "1".equals(SystemTools.getInstance().getValue("mobile_mail_only"));
		if (mark) {
			sql = " and (userEname=: userEname or email=:userEname or mobile=:userEname)";
		}
		String hql = this.userDao.getSql(2) + sql;
		MethodParam param = new MethodParam("ByUserEname", "", hql, entityName);
		param.setParams("userEname", userEname);
		if (mark) {
			param.setParams("email", userEname);
			param.setParams("mobile", userEname);
		}
		return (User) userDao.selectSingle(param);
	}

	//获取用户信息
	private User getUserByUserIdOrUserEname(User user) {
		MethodParam param = new MethodParam("ByUserAttr", "", "", entityName);
		StringBuffer sb = new StringBuffer();
		if (Validator.isNotNull(user.getUserEname())) {
			sb.append(" and userEname =:userEname");
			param.setParams("userEname", user.getUserEname());
		}
		if (Validator.isNotNull(user.getUserId())) {
			sb.append(" and userId =:userId");
			param.setParams("userId", user.getUserId());
		}
		if (Validator.isNotNull(user.getEmail())) {
			sb.append(" and email =:email");
			param.setParams("email", user.getEmail());
		}
		if (Validator.isNotNull(user.getMobile())) {
			sb.append(" and mobile =:mobile");
			param.setParams("mobile", user.getMobile());
		}
		if (!Validator.isNull(sb.toString())) {
			param.setSqlStr(userDao.getSql(2) + sb.toString());
			User userr = (User) userDao.selectSingle(param);
			return userr;
		} else {
			return null;
		}
	}

	//验证用户名,邮箱,手机号是否唯一
	private String getUserByUserEname(String userEname, String email, String mobile) {
		if (Validator.isNull(userEname))
			return "用户账号为空";
		String hql = this.userDao.getSql(2) + " and userEname=: userEname";
		MethodParam param = new MethodParam("ByUserEname", "", hql, entityName);
		param.setParams("userEname", userEname);
		if ("1".equals(SystemTools.getInstance().getValue("mobile_mail_only"))) {
			if (Validator.isNull(email)) {
				return "请填写用户Email信息";
			} else {
				hql += " or email=: email";
				param.setParams("email", email);
			}
			if (Validator.isNull(mobile)) {
				return "请填写用户手机号码";
			} else {
				hql += " or mobile=: mobile";
				param.setParams("mobile", mobile);
			}
		}
		User user = (User) userDao.selectSingle(param);
		if (!Validator.isEmpty(user)) {
			if (userEname.equals(user.getUserEname())) {
				return "用户账号[" + user.getUserEname() + "]已存在,请重新输入";
			}
			if ("1".equals(SystemTools.getInstance().getValue("mobile_mail_only"))) {
				if (email.equals(user.getEmail())) {
					return "用户Email:[" + email + "]已存在,请重新输入";
				}
				if (mobile.equals(user.getMobile())) {
					return "用户手机号:[" + mobile + "]已存在,请重新输入";
				}
			}
		}
		return "";
	}

	public Page getPageInfo(ParamsVo<User> vo) {
		String orderBy = vo.getKey();
		if (Validator.isNull(orderBy))
			orderBy = "create_time";
		MethodParam param = setMethodParams(vo, 2, orderBy);
		int pageSize = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageSize")), "10"));
		int pageIndex = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageIndex")), "1"));
		param.setPageIndex(pageIndex);
		param.setPageSize(pageSize);
		param.setOrderby(orderBy + " desc");
		Page page = userDao.pageSelect(param);
		return page;
	}

	public List<User> getList(ParamsVo<User> vo) {
		String orderBy = vo.getKey();
		if (Validator.isNull(orderBy))
			orderBy = "create_time";
		MethodParam param = setMethodParams(vo, 2, orderBy);
		param.setOrderby(orderBy + " desc");
		return userDao.select(param);
	}

	public long countInfo(ParamsVo<User> vo) {
		MethodParam param = setMethodParams(vo, 1, "");
		return userDao.count(param);
	}

	private MethodParam setMethodParams(ParamsVo<User> vo, int type, String orderBy) {
		String methodKey = Validator.getDefaultStr(vo.getMethodKey(), "ByProperty");
		StringBuffer sb = new StringBuffer(userDao.getSql(type));
		MethodParam param = new MethodParam(methodKey, "", "", entityName);
		User user = vo.getObj();
		if (Validator.isNotNull(String.valueOf(vo.getParams("orgIds")))) {
			param.setParams("orgIds", vo.getParams("orgIds").toString());
		}
		if (Validator.isEmpty(user))
			return param;
		if (Validator.isNotNull(user.getUserEname())) {
			sb.append(" and userEname like '%" + user.getUserEname() + "%'");
			param.setParams("userEname", user.getUserEname());
		}
		if (Validator.isNotNull(user.getUserCname())) {
			sb.append(" and userCname like '%" + user.getUserCname() + "%'");
			param.setParams("userCname", user.getUserCname());
		}

		if (!Validator.isEmpty(user.getUserStatus()) && user.getUserStatus() == -1) {
			sb.append(" and userStatus =:userStatus");
			param.setParams("userStatus", String.valueOf(user.getUserStatus()));
		}

		if (Validator.isNotNull(user.getSysEname())) {
			sb.append(" and sysEname =:sysEname");
			param.setParams("sysEname", user.getSysEname());
		}
		if (Validator.isNotNull(user.getOrgId())) {
			sb.append(" and orgId =:orgId");
			param.setParams("orgId", user.getOrgId());
		}
		if (Validator.isNotNull(user.getOrgEname())) {
			sb.append(" and orgEname =:orgEname");
			param.setParams("orgEname", user.getOrgEname());
		}
		if (Validator.isNotNull(user.getDeptId())) {
			sb.append(" and deptId =:deptId");
			param.setParams("deptId", user.getDeptId());
		}
		if (Validator.isNotNull(user.getAppUid())) {
			sb.append(" and appUid =:appUid");
			param.setParams("appUid", user.getAppUid());
		}
		if (Validator.isNotNull(user.getAppUname())) {
			sb.append(" and appUname =:appUname");
			param.setParams("appUname", user.getAppUname());
		}
		if (Validator.isNotNull(user.getUserType())) {
			sb.append(" and userType =:userType");
			param.setParams("userType", user.getUserType());
		}
		if (Validator.isNotNull(user.getUsbKey())) {
			sb.append(" and usbKey =:usbKey");
			param.setParams("usbKey", user.getUsbKey());
		}
		if (Validator.isNotNull(user.getProvince())) {
			sb.append(" and province =:province");
			param.setParams("province", user.getProvince());
		}
		if (Validator.isNotNull(user.getCity())) {
			sb.append(" and city =:city");
			param.setParams("city", user.getCity());
		}
		if (Validator.isNotNull(user.getAddress())) {
			sb.append(" and address =:address");
			param.setParams("address", user.getAddress());
		}
		if (Validator.isNotNull(user.getCompany())) {
			sb.append(" and company =:company");
			param.setParams("company", user.getCompany());
		}
		if (Validator.isNotNull(user.getPosition())) {
			sb.append(" and position =:position");
			param.setParams("position", user.getPosition());
		}
		if (Validator.isNotNull(user.getUserTitle())) {
			sb.append(" and userTitle =:userTitle");
			param.setParams("userTitle", user.getUserTitle());
		}
		if (Validator.isNotNull(user.getSpecField())) {
			sb.append(" and specField =:specField");
			param.setParams("specField", user.getSpecField());
		}
		if (Validator.isNotNull(user.getGraduate())) {
			sb.append(" and graduate =:graduate");
			param.setParams("graduate", user.getGraduate());
		}
		if (Validator.isNotNull(user.getSchool())) {
			sb.append(" and school =:school");
			param.setParams("school", user.getSchool());
		}
		if (Validator.isNotNull(user.getEducation())) {
			sb.append(" and education =:education");
			param.setParams("education", user.getEducation());
		}
		if (Validator.isNotNull(user.getBirthday())) {
			sb.append(" and birthday =:birthday");
			param.setParams("birthday", user.getBirthday());
		}
		if (Validator.isNotNull(user.getUserSex())) {
			sb.append(" and userSex =:userSex");
			param.setParams("userSex", user.getUserSex());
		}
		if (Validator.isNotNull(user.getCardType())) {
			sb.append(" and cardType =:cardType");
			param.setParams("cardType", user.getCardType());
		}
		if (Validator.isNotNull(user.getCardNum())) {
			sb.append(" and cardNum =:cardNum");
			param.setParams("cardNum", user.getCardNum());
		}
		if (Validator.isNotNull(user.getEmail())) {
			sb.append(" and email =:email");
			param.setParams("email", user.getEmail());
		}
		if (Validator.isNotNull(user.getPhone())) {
			sb.append(" and phone =:phone");
			param.setParams("phone", user.getPhone());
		}
		if (Validator.isNotNull(user.getMobile())) {
			sb.append(" and mobile =:mobile");
			param.setParams("mobile", user.getMobile());
		}
		if (Validator.isNotNull(user.getFax())) {
			sb.append(" and fax =:fax");
			param.setParams("fax", user.getFax());
		}

		if (Validator.isNotNull(user.getUserRemark())) {
			sb.append(" and userRemark =:userRemark");
			param.setParams("userRemark", user.getUserRemark());
		}

		if (Validator.isNotNull(user.getDelStatus())) {
			sb.append(" and delStatus =:delStatus");
			param.setParams("delStatus", user.getDelStatus());
		}
		if (Validator.isNotNull(user.getDeptName())) {
			sb.append(" and deptName =:deptName");
			param.setParams("deptName", user.getDeptName());
		}
		if (Validator.isNotNull(user.getBjcaUserid())) {
			sb.append(" and bjcaUserid =:bjcaUserid");
			param.setParams("bjcaUserid", user.getBjcaUserid());
		}
		if (Validator.isNotNull(user.getCustomerType())) {
			sb.append(" and customerType =:customerType");
			param.setParams("customerType", user.getCustomerType());
		}
		if (Validator.isNotNull(user.getCertType())) {
			sb.append(" and certType =:certType");
			param.setParams("certType", user.getCertType());
		}
		if (Validator.isNotNull(user.getCertNo())) {
			sb.append(" and certNo =:certNo");
			param.setParams("certNo", user.getCertNo());
		}
		if (Validator.isNotNull(user.getAuditStatus())) {
			sb.append(" and auditStatus =:auditStatus");
			param.setParams("auditStatus", user.getAuditStatus());
		}
		if (Validator.isNotNull(user.getAuditText())) {
			sb.append(" and auditText =:auditText");
			param.setParams("auditText", user.getAuditText());
		}
		if (Validator.isNotNull(user.getPicUrl())) {
			sb.append(" and picUrl =:picUrl");
			param.setParams("picUrl", user.getPicUrl());
		}
		if (Validator.isNotNull(user.getRegSource())) {
			sb.append(" and regSource =:regSource");
			param.setParams("regSource", user.getRegSource());
		}
		if (Validator.isNotNull(user.getRegIp())) {
			sb.append(" and regIp =:regIp");
			param.setParams("regIp", user.getRegIp());
		}
		if (Validator.isNotNull(orderBy)) {
			sb.append(" order by " + UctStringUtil.toCamelNamed(orderBy) + " desc");
		}
		param.setSqlStr(sb.toString());
		return param;
	}
}
